<!-- WeatherForecast.vue -->
<template>
  <div class="weather-forecast" v-if="weather.isLoaded">
    <img :src="weather.iconUrl" alt="天气图标">
    <span>{{ weather.description }}</span>
    <span>{{ weather.temp }}℃</span>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'WeatherForecast',
  setup() {
    const weather = ref({ 
      description: '', 
      temp: '', 
      iconUrl: '', 
      isLoaded: false 
    });

    const fetchWeather = async () => {
      try {
        const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
          params: {
            lat: 32.0604, // 纬度
            lon: 110.7262, // 经度
            appid: '441db2de5c86cba1063d3f25d8273451',
            units: 'metric',
            lang: 'zh_cn'
          }
        });
        console.log(response.data);
        
        weather.value = {
          description: response.data.weather[0].description,
          temp: Math.round(response.data.main.temp),
          iconUrl: `http://openweathermap.org/img/w/${response.data.weather[0].icon}.png`,
          isLoaded: true
        };

      } catch (error) {
        console.error('获取天气信息失败:', error);
        weather.value.isLoaded = false;
      }
    };

    onMounted(() => {
      fetchWeather();
    });

    return {
      weather
    };
  }
}
</script>

<style lang="scss" scoped>
.weather-forecast {
  display: flex;
  align-items: center;

  img {
    width: 42px;
    margin-right: 10px;
  }

  span {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    margin-right: 20px;
    color: #aaccdd;
  }
}
</style>